export default {
  config: {
    baseURL: "https://dtw.bingdou.site",
    custom: {
      ShowLoading: true,
      LoadingMask: false,
      LoadingText: "正在加载",
    },
    dataType: "json",
    responseType: "text",
    timeout: 60000,
    withCredentials: false,
  },
  get(url, data, options) {
    if (!options) {
      options = {};
    }
    options.url = url;
    options.data = data;
    options.method = "GET";
    return this.request(options);
  },
  post(url, data, options) {
    if (!options) {
      options = {};
    }
    options.url = url;
    options.data = data;
    options.method = "POST";
    return this.request(options);
  },
  request(options) {
    let config = Object.assign(this.config, options);
    if (config.custom.ShowLoading) {
      uni.showLoading({
        title: config.custom.LoadingText || "正在加载",
        mask: config.custom.LoadingMask,
      });
    }
    config.url = config.baseURL + config.url;
    config.data = Object.assign({}, config.data);
    let open_id = uni.getStorageSync("open_id") || "";
    if (open_id) {
      config.data["open_id"] = open_id;
    }
    config.data["timestamp"] = Math.round(new Date() / 1000);
    return new Promise((resolve, reject) => {
      uni.request(config).then((res) => {
        if (config.custom.ShowLoading) {
          uni.hideLoading();
        }
        if (res.statusCode === 200) {
          let result = res.data;
          if (result.code === 0) {
            resolve(result);
          } else if (result.code === 50001) {
            uni.showToast({
              title: "当前未登录",
              icon: "none",
            });
            setTimeout(function () {
              uni.navigateTo({
                url: "/pages/login/index",
              });
            }, 1000);
          }
        } else {
          uni.showToast({
            title: `请求出错${res.statusCode}`,
            icon: "none",
          });
        }
      });
    });
  },
};
